<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/attendance.php';

// 检查权限
$auth = getAuth();
$auth->requireLogin();

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 处理打卡请求
if ($_POST) {
    $action = $_POST['action'] ?? '';
    $attendance = getAttendance();
    
    if ($action === 'clock_in') {
        $result = $attendance->clockIn($currentUser['id']);
    } elseif ($action === 'clock_out') {
        $result = $attendance->clockOut($currentUser['id']);
    } else {
        $result = ['success' => false, 'message' => '无效的操作'];
    }
    
    // 设置结果消息
    if ($result['success']) {
        $_SESSION['success_message'] = $result['message'];
        if (isset($result['time'])) {
            $_SESSION['success_message'] .= " 时间: " . $result['time'];
        }
        if (isset($result['status'])) {
            $statusLabels = [
                'normal' => '正常',
                'late' => '迟到',
                'early_leave' => '早退'
            ];
            $_SESSION['success_message'] .= " 状态: " . ($statusLabels[$result['status']] ?? $result['status']);
        }
    } else {
        $_SESSION['error_message'] = $result['message'];
    }
    
    // 重定向回仪表板
    header('Location: dashboard.php');
    exit;
} else {
    // 如果不是POST请求，重定向到仪表板
    header('Location: dashboard.php');
    exit;
}
?>
